package com.calc.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

public class ActivityUtils {

    private static Button.OnTouchListener buttonTouchVibratorListener = null;

    private ActivityUtils() {}


    /**
     * 从配置文件中读取是否需要震动反馈
     * @param ctx
     * @return
     */
    public static Boolean getVibratorByPreference(Context ctx) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
        return sp.getBoolean("click_vibrate", false);
    }

    /**
     * 生成按钮触摸振动事件
     * @param ctx 相关上下文
     * @return
     */
    private static Button.OnTouchListener generateButtonVibratorListener(final Context ctx) {
        Button.OnTouchListener tt = null;
        if(getVibratorByPreference(ctx)){
            tt = new Button.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    Vibrator vibrator = (Vibrator)ctx.getSystemService(Context.VIBRATOR_SERVICE);
                    vibrator.vibrate(50);
                    return false;
                }
            } ;
        }
        return tt;
    }

    /**
     * 获取单例的震动反馈事件
     * @param ctx
     * @param flag
     * @return
     */
    public synchronized static Button.OnTouchListener getButtonVibratorListener(final Context ctx, boolean flag) {
        if(buttonTouchVibratorListener == null) {
            buttonTouchVibratorListener = generateButtonVibratorListener(ctx);
        }
        return buttonTouchVibratorListener;
    }

}
